package com.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.server.GameServer;
import com.server.MatchServer;
import com.server.ServletUrlTools;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/match/*")
public class MatchServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        String url=req.getRequestURI();
        String reqMethod=req.getMethod();

        url=ServletUrlTools.unescape(url);System.out.println(url);
        String[] urls= url.split("/");

        resp.setCharacterEncoding("UTF-8");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers", "*");
        resp.setHeader("Access-Control-Allow-Credentials", "true");

        JSONObject rmsg=new JSONObject();
        String userName="";
        String gameId="";
        if(reqMethod.equals("GET")){//
            if(urls.length==5){
                //询问匹配状态**GET /match/{gameId}/{userName}/opponent
                //返回字符串，success,fail,waiting
                gameId=urls[2];
                userName=urls[3];
                resp.getWriter().write(MatchServer.getMatchState(userName,gameId));
                System.out.println(userName+" get gameState:"+gameId);
                return;
            }else{
                //请求云端游戏状态**GET /match/{gameId}/{userName}
                //返回 {version:"",game_state:""};
                gameId=urls[2];
                userName=urls[3];
                rmsg=GameServer.getMsg(userName,gameId);
            }
        }else if(reqMethod.equals("POST")){
            //请求开始匹配**POST /match/{userName}
            //返回{match_handle,"gameId"}
            userName=urls[2];
            gameId=MatchServer.getMatch(userName);
            rmsg.put("match_handle",gameId);
        }else if(reqMethod.equals("DELETE")){
            if(urls.length==4){
                //中途取消匹配**DELETE /match/{userName}
                MatchServer.cancelMatch(userName);
                System.out.println(userName+" cancel Match");
            }else{
                //玩家退出这个棋局**DELETE /match/{gameId}/{userName}
                userName=urls[2];
                GameServer.quitGame(userName);
                System.out.println(userName+" quit game");
            }
        }else if(reqMethod.equals("PUT")){
            //推送状态到云端 **PUT /match/{gameId}/{userName}
            //body {version:"",game_state:""};
            gameId=urls[2];
            userName=urls[3];
            JSONObject msg=JSONObject.parseObject(req.getReader().readLine());
            GameServer.sendMsg(userName,gameId,msg);
            System.out.println(userName+" put msg to game:"+gameId);
            return;
        }

        if(rmsg!=null){
            resp.getWriter().write(rmsg.toJSONString());
            System.out.println("user answered:"+userName+"->"+rmsg);
        }

    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers", "*");
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Allow","OPTIONS, GET, PUT");
    }
}
